package com.dxy.lc.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
@Component
public class MD5Util {

    private static int repeat;//重复次数
    private static String salt;//盐值

    @Value("${pwd.conf.encryptRepeat:10}")
    public void setRepeat(int repeat) {
        MD5Util.repeat = repeat;
    }

    @Value("${pwd.conf.encryptSalt:sjaiohgioae}")
    public void setSalt(String salt) {
        MD5Util.salt = salt;
    }

    private static MessageDigest MD5_DIGEST;//MD5加密
    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();//加密器

    //初始化
    static {
        try {
            MD5_DIGEST = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String getEncryptPassword(String password) {
        String saltPassword = "{" + salt + "}" + password;
        for (int i = 0; i < repeat; i++) {
            saltPassword = BASE64_ENCODER.encodeToString(MD5_DIGEST.digest(saltPassword.getBytes()));
        }
        return saltPassword;
    }

    public static void main(String[] args) {
        MD5Util.repeat = 10;
        MD5Util.salt = "sjaiohgioae";
        System.out.println(MD5Util.getEncryptPassword("123456"));
    }
}
